$(document).ready(function () {
    let imagePairs = {};
    let currentIndex = 0;
    let prefixes = [];

    $.get("/get_images", function (data) {
        imagePairs = data;
        prefixes = Object.keys(imagePairs);
        if (prefixes.length > 0) {
            loadImages(prefixes[currentIndex]);
        }
    });

    function loadImages(prefix) {
        $("#image-container").html("<div class='loading'>Loading...</div>");
        const images = imagePairs[prefix];
        if (images && images.length === 2) {
            $("#image-container").html(`
                <div class="image-wrapper">
                    <img id="image1" src="/static/images/${images[0]}" alt="Image 1">
                    <img id="image2" src="/static/images/${images[1]}" alt="Image 2">
                </div>
                <input type="range" id="slider" min="0" max="100" value="50">
            `);

            $("#slider").on("input", function () {
                const value = $(this).val();
                $("#image2").css("clip-path", `inset(0 0 0 ${value}%)`);
            });
        }
    }

    $("#next").click(function () {
        if (currentIndex < prefixes.length - 1) {
            currentIndex++;
            loadImages(prefixes[currentIndex]);
        }
    });

    $("#prev").click(function () {
        if (currentIndex > 0) {
            currentIndex--;
            loadImages(prefixes[currentIndex]);
        }
    });

    $(document).keydown(function (e) {
        if (e.key === "ArrowRight") {
            $("#next").click();
        } else if (e.key === "ArrowLeft") {
            $("#prev").click();
        }
    });
});